<?php

require_once 'MainPageWidget.php';
class MenuWidget extends MainPageWidget
{
	public $title = 'Меню';
	public $items = array();
	public $tdis = array();

	public function Render()
	{
		foreach ($this->getTdis($this->getParam('tdis', array())) as $v) {
			$this->addMenuItem($this->buildMenuItemFromTdi($v));
		}
		return $this;
	}
	public function addMenuItem ($mi)
	{
		$this->items[] = $mi;
	} // end of method addMenuItem

	public function buildMenuItemFromTdi ($tdi)
	{
		$mi = $tdi;
		$mi['url']  = $this->tdiUrl($tdi['url']);
		return $mi;
	} // end of method buildMenuItemFromTdi
	public function getTdis ($where_tdis=NULL)
	{
		$tdis = array();

		if (!$where_tdis || (is_array($where_tdis) && in_array(-1, $where_tdis))) {
			$fake_section = $this->store->create("ftdi", array("title"=>"Все записи", 'url' => 'showfeed'));
			$fake_section->id = -1;
			$tdis[] = $this->buildChecklistItemFromTdi($fake_section);
		}

		$community_oid = $this->getParam('community_oid', $this->acl_assistant->acl_data['comity_oid']);
		if (is_array($where_tdis) && $where_tdis) {
			$ql = "select objects where tdi.community_oid = :0 and tdi.oid in :1 and is_deleted = 0";
			$results = $this->store->find( $ql, array($community_oid, $where_tdis) );
		} else {
			$ql = "select objects where tdi.community_oid = :0 and is_deleted = 0";
			$results = $this->store->find( $ql, array($community_oid));
		}
		while ($tdi = $results->next()) {
			$tdis[] = $this->buildChecklistItemFromTdi ($tdi);
		}

		return $tdis;
	} // end of method getTdis

	public function tdiUrl ($url)
	{
		$this->ctx->rh->UseClass('RL_URLGenerator');
		$router = $this->ctx->rh->router;
		$params = $this->parent->params;
		$params['tdi_url'] = $url;
		$ug = new RL_URLGenerator($router->getRule('community_tdi'));
		$ug->setRouter($router);
		$ug->setParams($params);
		return $ug->generateUrl();
	} // end of method tdiUrl

	public function settingsForm ()
	{
		$tdis_list = $this->getTdis();

		$config['form'] = array(
			'title' => 'Настройка меню',
			'fields' => array(

				'title' => array(
					'type' => 'text',
					'title' => 'Название',
					'default' => $this->title,
					'description' => 'Название меню',
				),

				'tdis' => array(
					'type' => 'checklist',
					'title' => 'Список разделов',
					'description' => 'Разделы сообщества',
					'fields' => $tdis_list,
				),
			),
		);
		return $config['form'];
	}

}

